public without sharing class SalesPerformanceDataSheetHandler {
  	

  	//自动生成唯一主键 并统计 调整的编号
    public static void generateOnlyKey(List<SalesPerformanceDataSheet__c> spList  ){

    	//设置唯一主键
		Map<String,String> keysMap = new Map<String,String >();
		Set<Id> mset = new Set<Id>();
		Set<Id> exset = new Set<Id>();
        Set<String> accset = new Set<String>();
        Set<String> userset = new Set<String>();


    	for (SalesPerformanceDataSheet__c sp : spList) {
    		
    		if(sp.SalesPerformanceDataSheet__c != null){
    			mset.add(sp.SalesPerformanceDataSheet__c);

    			if(sp.Id != null ) exset.add(sp.Id );
                
    		}
            if(sp.AccountPK__c != null )accset.add(sp.AccountPK__c);
            if(sp.TerminalAccountPK__c != null )accset.add(sp.TerminalAccountPK__c);

            if(sp.EmployeeNumber__c != null )userset.add(sp.EmployeeNumber__c);

    		
    	}

        //System.debug(accset);

        Map<String,Id> accMap = getAccMap(accset);
        Map<String,Id> userMap = getUserMap(userset);
        //System.debug(accMap.keySet());
        User manager= [select Id from User where Name =:Label.BudgetNotMatchOwner limit 1];

    	//如果存在调整的数据 去检查有几条调整的数 

    	Map<String,Integer> cntMap =new Map<String,Integer>();

    	for ( AggregateResult sp:[select count(Id) cnt ,  SalesPerformanceDataSheet__c from SalesPerformanceDataSheet__c 

    		where SalesPerformanceDataSheet__c in:mset and Id not in:exset  group by SalesPerformanceDataSheet__c    ] ) {
    		
    		cntMap.put(String.valueOf(sp.get('SalesPerformanceDataSheet__c')), Integer.valueOf(sp.get('cnt')));
    		
    	}


    	for (SalesPerformanceDataSheet__c sp : spList) {

    		if(sp.SalesPerformanceDataSheet__c != null  ){

    			if(sp.AdjustNo__c  == null )sp.AdjustNo__c = cntMap.containsKey( sp.SalesPerformanceDataSheet__c ) ? cntMap.get(sp.SalesPerformanceDataSheet__c )+1 : 1;

    		}
    		sp.Only__c =    getKeyWithOutAdjustNo(sp)+sp.RecordTypeId +sp.SalesPerformanceDataSheet__c +sp.AdjustNo__c;
            if(sp.AccountPK__c != null )sp.Account__c = accMap.get(sp.AccountPK__c);
            if(sp.TerminalAccountPK__c != null )sp.TerminalAccount__c = accMap.get(sp.TerminalAccountPK__c);
            sp.OwnerId = userMap.containsKey(sp.EmployeeNumber__c)  && userMap.get(sp.EmployeeNumber__c) != null ? userMap.get(sp.EmployeeNumber__c) : manager.Id ;
    	}


    }
    //匹配 客户
    public static  Map<String,Id> getAccMap(Set<String> accset ){

         Map<String,Id> accMap = new  Map<String,Id> ();
         if(accset == null || accset.isEmpty())return accMap;
         for (Account acc  :[select Id ,NCICCode__c from Account where NCICCode__c in:accset or Id in:accset] ) {
             accMap.put(acc.NCICCode__c, acc.Id);
             accMap.put(acc.Id,acc.Id);
         }
         return accMap;

    }

    //匹配人员
    public static Map<String,Id> getUserMap (Set<String> userset){
         Map<String,Id> userMap  = new  Map<String,Id> ();
         if(userset == null || userset.isEmpty())return userMap;


         for (User u  :[select Id ,EmployeeNumber,IsActive,ManagerId  from User where EmployeeNumber in:userset  ] ) {
             userMap.put(u.EmployeeNumber, u.IsActive ? u.Id : u.ManagerId);
             
         }
         return userMap;
    }

    //生成主键
    public static String getKeyWithOutAdjustNo(SalesPerformanceDataSheet__c sp ){
    	return sp.Year__c+sp.Quarter__c+sp.Company__c+sp.Province__c + sp.AccountPK__c+sp.TerminalAccountPK__c
    		
    		+sp.InstrumentClasses__c+sp.ReagentCategory__c+sp.JobCategory__c+sp.IncrementalCcategory__c+sp.EmployeeNumber__c+sp.Category__c+sp.CompanyName__c + sp.Department__c
    		+sp.AssessmentCategory__c+sp.SalesMarket__c ;
    }
    
    //如果其他季度不为空
    public static List<SalesPerformanceDataSheet__c> divide(SalesPerformanceDataSheet__c sp,Integer currentq  ){
        
        List<SalesPerformanceDataSheet__c> spL = new List<SalesPerformanceDataSheet__c>();

        //如果 存在一季度不为空的数据 则生成一条 1季度的数据  并清空其他季度的数据 
        if(( (sp.LastYearSalesVolumeQ1__c != null && sp.LastYearSalesVolumeQ1__c != 0 ) 
            || (sp.ActualQuantityQ1__c != null && sp.ActualQuantityQ1__c != 0 )
            || (sp.BudgetQuantityQ1__c != null && sp.BudgetQuantityQ1__c != 0  )
            || (sp.ActualSalesQ1__c != null && sp.ActualSalesQ1__c != 0  )
            || (sp.BudgetSalesQ1__c != null && sp.BudgetSalesQ1__c != 0  )  )&& currentq == 1) spL.add(clone(sp,currentq, 1 ));


         if(((sp.LastYearSalesVolumeQ2__c != null && sp.LastYearSalesVolumeQ2__c != 0 ) 
            || (sp.ActualQuantityQ2__c != null && sp.ActualQuantityQ2__c != 0 )
            || (sp.BudgetQuantityQ2__c != null && sp.BudgetQuantityQ2__c != 0  )
            || (sp.ActualSalesQ2__c != null && sp.ActualSalesQ2__c != 0  )
            || (sp.BudgetSalesQ2__c != null && sp.BudgetSalesQ2__c != 0  ))&& currentq <= 2) spL.add(clone(sp, currentq,2 ));

         if(((sp.LastYearSalesVolumeQ3__c != null && sp.LastYearSalesVolumeQ3__c != 0 ) 
            || (sp.ActualQuantityQ3__c != null && sp.ActualQuantityQ3__c != 0 )
            || (sp.BudgetQuantityQ3__c != null && sp.BudgetQuantityQ3__c != 0  )
            || (sp.ActualSalesQ3__c != null && sp.ActualSalesQ3__c != 0  )
            || (sp.BudgetSalesQ3__c != null && sp.BudgetSalesQ3__c != 0  ))&& currentq <= 3) spL.add(clone(sp,currentq,3 ));

         if(((sp.LastYearSalesVolumeQ4__c != null && sp.LastYearSalesVolumeQ4__c != 0 ) 
            || (sp.ActualQuantityQ4__c != null && sp.ActualQuantityQ4__c != 0 )
            || (sp.BudgetQuantityQ4__c != null && sp.BudgetQuantityQ4__c != 0  )
            || (sp.ActualSalesQ4__c != null && sp.ActualSalesQ4__c != 0  )
            || (sp.BudgetSalesQ4__c != null && sp.BudgetSalesQ4__c != 0  ))&& currentq <= 4) spL.add(clone(sp,currentq, 4 ));

        return spL;

    }

    //拷贝 并置空其他季度的数据 
    public static SalesPerformanceDataSheet__c clone(SalesPerformanceDataSheet__c sp, Integer currentq ,Integer q  ){
        
        SalesPerformanceDataSheet__c targetSp = sp.clone();
        targetSp.SalesPerformanceDataSheet__c = sp.Id;
        targetSp.SalesPerformanceAdjustment__c = null;
        targetSp.Quarter__c = String.valueOf(q);

        targetSp.FutureAdjust__c = currentq < q ;

        targetSp.NotActive__c = currentq != q ;

        if(sp.RecordType.DeveloperName  == 'InstrumentPerformanceAdjust' ) targetSp.NotActive__c  =  false  ;


        Set<String> s  = new Set<String>{'LastYearSalesVolume','ActualQuantity','BudgetQuantity','ActualSales','BudgetSales'};
    
        for(Integer i = 1 ; i <= 4 ; i ++){
           if(i == q)continue;
            
            for(String f : s ){
                targetSp.put(f+'Q'+i+'__c', null);
                
            }
        }
        return targetSp;

    }

    //审批通过将调整的改为有效
    public static void adjustAppoval(List<SalesPerformanceAdjustment__c> spList ,Map<Id,SalesPerformanceAdjustment__c> oldMap ){

    	Set<String >mset  = new Set<String>();
    	for(SalesPerformanceAdjustment__c sp: spList  ){
    		SalesPerformanceAdjustment__c old = oldMap.get(sp.Id);
    		if(sp.Status__c == '审批成功' && old.Status__c != sp.Status__c){
    			mset.add(sp.Id);
    		}
    	}
    	if(mset.isEmpty())return;
    	//调整明细
    	Set<Id> newset = new Set<Id>();
    	Set<Id> spset = new Set<Id>();
    	//将绩效调整数据变为有效

        List<SalesPerformanceDataSheet__c>inList = new List<SalesPerformanceDataSheet__c>();


        Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        String sql = 'select ';
        List<String> fields = new List<String>();
        for (String field : fieldMap.keySet()) {
             fields.add(field);
        }
        sql += String.join(fields, ',');

        sql += ' , RecordType.DeveloperName from SalesPerformanceDataSheet__c ';

        List<SalesPerformanceDataSheet__c> upList = new List<SalesPerformanceDataSheet__c>();

    	for (SalesPerformanceDataSheet__c sp: Database.query(sql +' where   SalesPerformanceAdjustment__c in (\'' +String.join(new List<String>(mset), '\',\'') +'\') ' ) ) {
    		
            List<SalesPerformanceDataSheet__c>  spL = divide(sp,Integer.valueOf(sp.Quarter__c));
            //原始数据 
            if(sp.SalesPerformanceDataSheet__c != null )spset.add(sp.SalesPerformanceDataSheet__c);
            newset.add(sp.Id);
            inList.addAll(spL);
            //if(!spL.isEmpty())continue;
           // sp.NotActive__c = spL.isEmpty() ? false : true  ;
            //System.debug('apppovl==>'+sp.NotActive__c + ' '+ spL.isEmpty() +' '+sp.Id );
            upList.add(new SalesPerformanceDataSheet__c(Id=sp.Id  ,NotActive__c = true    ));

    	}
    	//将绩效基础数据变为失效
    	for (Id spId  :spset ) {
           //System.debug('apppovl==>'+ spId );

    		upList.add(new SalesPerformanceDataSheet__c(Id=spId ,NotActive__c = true ));
    	}


    	//将之前的调整数据变为失效 
    	for (SalesPerformanceDataSheet__c sp: [select Id from SalesPerformanceDataSheet__c 
            where  NotActive__c = false and SalesPerformanceDataSheet__c not in:newset and SalesPerformanceDataSheet__r.SalesPerformanceDataSheet__c in:spset   ] ) {
    		
            sp.NotActive__c = true;
    		upList.add(sp);

    	}
        
        System.debug('adjustAppoval=>'+upList);
    	if(!upList.isEmpty())update upList;
        if(!inList.isEmpty())insert inList;


    }
    

}